import axios from 'axios'
import { ElMessage } from 'element-plus'
import { diffTokenTime } from '@/utils/auth'
import store from '@/store'

const service = axios.create({
  baseURL: "http://101.43.15.9:9100/api/changan",
  timeout: 5000
})

service.interceptors.request.use(
  (config) => {
    if (window.sessionStorage.getItem('token')) {
      if (diffTokenTime()) {
        store.dispatch('app/logout')
        return Promise.reject(new Error('token 失效了'))
      }
    }
    config.headers.Authorization = localStorage.getItem('token')
    // config.headers.Authorization = window.sessionStorage.getItem('token')
    return config
  },
  (error) => {
    return Promise.reject(new Error(error))
  }
)

service.interceptors.response.use(
  (response) => {
    const { data, meta } = response
    if (window.sessionStorage.getItem('token') && data.status == 900) {
      if (diffTokenTime()) {
        store.dispatch('app/logout')
        ElMessage.error(meta.msg)
        return Promise.reject(new Error('token 失效了'))
      }
    }
    return data
  },
  (error) => {
    console.log('error', error.response)
    if (error.response.data.code == -1) {
      store.dispatch('app/logout')
      ElMessage.error('登录过期，请重新登录')
      return Promise.reject(new Error('token 失效了'))
    }
    error.response && ElMessage.error(error.response.data)
    return Promise.reject(new Error(error.response.data))
  }
)
export default service
